package com.cdu.eduPanda.project.interceptor;

import com.cdu.eduPanda.project.common.biz.user.UserContext;
import com.cdu.eduPanda.project.common.biz.user.UserInfoDTO;
import com.cdu.eduPanda.project.common.convention.exception.ClientException;
import com.cdu.eduPanda.project.config.JWTProperties;
import com.cdu.eduPanda.project.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import static com.cdu.eduPanda.project.common.constant.RedisCacheConstant.USER_LOGIN_KEY;

@Component
@RequiredArgsConstructor
@Slf4j
public class UserTransmitInterceptor implements HandlerInterceptor {

    private final JWTProperties jwtProperties;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌
        String token=request.getHeader("token");

        //2、校验令牌
        try {
            Claims claims = JWTUtil.parseJWT(jwtProperties.getSecretKey(), token);
            UserInfoDTO userInfoDTO = UserInfoDTO.builder()
                    .userId(claims.get("id").toString())
                    .username(claims.get("username").toString())
                    .build();
            UserContext.setUser(userInfoDTO);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }finally {
            UserContext.removeUser();
        }
    }
}
